﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Text;
using System.Data;
using System.Xml.Linq;
using System.IO;
using PushSharp;
using System.Configuration;

namespace Zatify.API.Controllers
{
    public class UserController : BaseController
    {
        public string Login1(string ID)
        {
            var doc = CommonLib.ErrorXml("Invalid login or password", "1");

                ID = Encoding.UTF8.GetString(Convert.FromBase64String(ID));

            string[] userpass = ID.Split(';');

            if (userpass.Length != 2)
                return doc.ToString();

            DataTable dt;
                dt = DataAccess.GetDataTable("spAPI_User_Login", new string[] { "LoginName", "Password" }, new object[] { userpass[0], userpass[1] });

            if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 1)
            {
                return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() });
            }
            return doc.ToString();
        }

        public string Login(string ID)
        {
            try
            {
                var doc = CommonLib.ErrorXml("Invalid login or password", "1");

                try
                {
                    ID = Encoding.UTF8.GetString(Convert.FromBase64String(ID));
                }
                catch
                {
                    return doc.ToString();
                }

                string[] userpass = ID.Split(';');

                if (userpass.Length != 2)
                    return doc.ToString();

                DataTable dt;
                try
                {
                    dt = DataAccess.GetDataTable("spAPI_User_Login", new string[] { "LoginName", "Password" }, new object[] { userpass[0], userpass[1] });
                }
                catch
                {
                    return doc.ToString();
                }

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 1)
                {
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() });
                }
                return doc.ToString();
            }
            catch (Exception ex)
            {
                CommonLib.SendEmail("oleg.boligatov@gmail.com", "vmacari@gmail.com", "unexpected error login", ex.Message + "<br/><br/><br/>" + ex.StackTrace);
                throw;
            }
        }

        public string GetID(string Login, string Pass)
        {
            string result = Login + ";" + Pass;
            result = Convert.ToBase64String(Encoding.UTF8.GetBytes(result));
            return result;
        }

        public string PasswordRecover(string email, string phone)
        {
            var doc = CommonLib.OkXml();

            if (!string.IsNullOrEmpty(email))
            {
                string filePath = Server.MapPath(VirtualPathUtility.ToAbsolute("~/EmailTemplates/")) + "PasswordRecover.html";
                string message = System.IO.File.ReadAllText(filePath);
                
                DataTable dt;
                try
                {
                    dt = DataAccess.GetDataTable("spAPI_User_PasswordRecover", new string[] { "Email" }, new object[] { email });

                    if (!dt.Rows[0].IsNull("Login"))
                    {
                        message = message.Replace("%username%", dt.Rows[0]["Login"].ToString()).Replace("%password%", dt.Rows[0]["Password"].ToString());
                        CommonLib.SendEmail(email, "", "Zatify Password Recover", message);
                    }
                    else
                    {
                        return CommonLib.ErrorXml("Email not found", "101").ToString();
                    }
                }
                catch (Exception ex)
                {
                    return CommonLib.ErrorXml(ex.Message, "100").ToString();
                }
            }

            if (!string.IsNullOrEmpty(phone))
            {
                string filePath = Server.MapPath(VirtualPathUtility.ToAbsolute("~/EmailTemplates/")) + "PasswordRecover.txt";
                string message = System.IO.File.ReadAllText(filePath);

                DataTable dt;
                try
                {
                    dt = DataAccess.GetDataTable("spAPI_User_PasswordRecover", new string[] { "Phone" }, new object[] { phone });

                    if (!dt.Rows[0].IsNull("Login"))
                    {
                        message = message.Replace("%username%", dt.Rows[0]["Login"].ToString()).Replace("%password%", dt.Rows[0]["Password"].ToString());
                        SmsSendService.SendSms(message, phone);
                    }
                    else
                    {
                        return CommonLib.ErrorXml("Phone not found", "101").ToString();
                    }
                }
                catch (Exception ex)
                {
                    return CommonLib.ErrorXml(ex.Message, "100").ToString();
                }
            }



            return doc.ToString();
        }

        public string Register(string id, string email, string zip, string phone, string referred)
        {
            string[] userpass = null;

            try
            {
                id = Encoding.UTF8.GetString(Convert.FromBase64String(id));
                userpass = id.Split(';');

                if (string.IsNullOrEmpty(email))
                    email = "";
                if (string.IsNullOrEmpty(phone))
                    phone = "";
                if (string.IsNullOrEmpty(referred))
                    referred = "";

                List<string> paramName = new List<string>();
                List<object> paramValue = new List<object>();

                paramName.Add("LoginName");
                paramValue.Add(userpass[0]);

                paramName.Add("Password");
                paramValue.Add(userpass[1]);

                paramName.Add("Email");
                paramValue.Add(email);

                paramName.Add("ZipCode");
                paramValue.Add(zip);

                paramName.Add("Phone");
                paramValue.Add(phone);

                paramName.Add("ReferredBy");
                paramValue.Add(referred);

                if (Request.ContentLength > 0)
                {
                    paramName.Add("PhotoContentType");
                    paramValue.Add(Request.ContentType);

                    paramName.Add("Photo");
                    paramValue.Add(Request.BinaryRead(Request.ContentLength));
                }

                DataTable dt = DataAccess.GetDataTable("spAPI_User_Register",
                    paramName.ToArray(), paramValue.ToArray());

                switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                {
                    case 0:
                        return CommonLib.ErrorXml("Referrer is not found", "3").ToString();
                    case -1:
                        return CommonLib.ErrorXml("Phone already exists", "4").ToString();
                    case -2:
                        return CommonLib.ErrorXml("Email already exists", "5").ToString();
                    case -3:
                        return CommonLib.ErrorXml("Invalid zip code", "6").ToString();
                    default:
                        return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["SecurityToken"].ToString() }).ToString();
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("PK_UserBusinessLogins"))
                {
                    return CommonLib.ErrorXml(string.Format("Login '{0}' already exists", userpass[0]), "1").ToString();
                }
                else
                {
                    return CommonLib.ErrorXml(ex.Message, "100").ToString();
                }                
            }
        }

        public string SetProfileCategories(string token, string categories)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_UserCategory_Update",
                    new string[] { "Token", "Categories" }, new object[] { token, categories });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml().ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string GetProfile(string token)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_User_GetProfile",
                    new string[] { "Token" }, new object[] { token });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string UpdateProfile(string token, string userid, string email, string phone, string zip)
        {
            try
            {
                List<string> paramName = new List<string>();
                List<object> paramValue = new List<object>();
                
                paramName.Add("Token");
                paramValue.Add(token);

                if (userid != null)
                {
                    userid = Encoding.UTF8.GetString(Convert.FromBase64String(userid));
                    string[] userpass = userid.Split(';');
                    if (userpass.Length == 2)
                    {
                        paramName.Add("Password");
                        paramValue.Add(userpass[1]);
                    }
                }

                if (email != null)
                {
                    paramName.Add("Email");
                    paramValue.Add(email);
                }

                if (phone != null)
                {
                    paramName.Add("Phone");
                    paramValue.Add(phone);
                }

                if (Request.ContentLength > 0)
                {
                    paramName.Add("PhotoContentType");
                    paramValue.Add(Request.ContentType);

                    paramName.Add("Photo");
                    paramValue.Add(Request.BinaryRead(Request.ContentLength));
                }

                if (zip != null)
                {
                    paramName.Add("zip");
                    paramValue.Add(zip);
                }

                DataTable dt = DataAccess.GetDataTable("spAPI_User_UpdateProfile",
                    paramName.ToArray(), paramValue.ToArray());

                switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                {
                    case 1:
                        return CommonLib.OkXml().ToString();
                    case -3:
                        return CommonLib.ErrorXml("Invalid Zip code", "2").ToString();
                    case -2:
                        return CommonLib.ErrorXml("Email already exists (in users or in buisnesses)", "9").ToString();
                    case -5:
                        return CommonLib.ErrorXml("Phone already exists (in users or in buisnesses)", "10").ToString();
                    default:
                        return CommonLib.ErrorXml("Invalid token", "1").ToString();
                }
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string SaveSettings(string token, string alertmode)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_UserSetting_Update",
                    new string[] { "Token", "Setting", "Value" }, new object[] { token, "AlertMode", alertmode });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml().ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string GetSettings(string token)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_UserSetting_GetList",
                    new string[] { "Token" }, new object[] { token });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string GetSelectedCategories(string token)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_UserCategory_GetList",
                    new string[] { "Token" }, new object[] { token });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string DeleteBusinessesFromFavorites(string token, string businesses)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_UserFavorites_Delete",
                    new string[] { "Token", "Businesses" }, new object[] { token, businesses });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml().ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string AddFavoriteBusinesses(string token, string businesses)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_UserFavorites_Add",
                    new string[] { "Token", "Businesses" }, new object[] { token, businesses });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml().ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string GetFavorites(string token, decimal? lat, decimal? @long)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_UserFavorites_GetList",
                    new string[] { "Token", "Latitude", "Longtitude" }, new object[] { token, lat, @long });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public ActionResult GetProfilePhoto(string token)
        {
            if (!CommonLib.UserCheckToken(token))
            {
                return null;
            }

            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_User_GetProfilePhoto",
                    new string[] { "Token" }, new object[] { token });
                return this.Image((byte[])dt.Rows[0]["Photo"], dt.Rows[0]["PhotoContentType"].ToString());
            }
            catch { return null; }
        }

        public ActionResult GetProfilePictureById(int userId)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_User_GetProfilePictureById",
                    new string[] { "UserId" }, new object[] { userId });
                return this.Image((byte[])dt.Rows[0]["Photo"], dt.Rows[0]["PhotoContentType"].ToString());
            }
            catch { return null; }
        }
        
        public string AddBusinessReview(string token, int businessid, string text, int rating)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_BusinessReview_Add",
                    new string[] { "Token", "BusinessId", "ReviewText", "Rating" }, new object[] { token, businessid, text, rating });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml().ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string AddPromotionReview(string token, int promotionid, string text, int rating)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_PromotionReview_Add",
                    new string[] { "Token", "PromotionId", "ReviewText", "Rating" }, new object[] { token, promotionid, text, rating });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml().ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string LikeBusiness(string token, int businessid)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Business_Like",
                    new string[] { "Token", "BusinessId" }, new object[] { token, businessid });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml().ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string DislikeBusiness(string token, int businessid)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Business_Dislike",
                    new string[] { "Token", "BusinessId" }, new object[] { token, businessid });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml().ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string LikePromotion(string token, int promotionid)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Promotion_Like",
                    new string[] { "Token", "PromotionId" }, new object[] { token, promotionid });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml().ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string DislikePromotion(string token, int promotionid)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Promotion_Dislike",
                    new string[] { "Token", "PromotionId" }, new object[] { token, promotionid });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml().ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string BlockBusiness(string token, string businessId)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_BlockBusiness_Update",
                    new string[] { "Token", "BusinessId" }, new object[] { token, businessId });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml().ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string BlockPromotion(string token, string promotionId)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_BlockPromotion_Update",
                    new string[] { "Token", "PromotionId" }, new object[] { token, promotionId });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml().ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string BlockCategory(string token, string categoriesId)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_BlockCategory_Update",
                    new string[] { "Token", "CategoriesId" }, new object[] { token, categoriesId });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml().ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string Ping(string token, decimal latitude, decimal longtitude, DateTime? localTime, string deviceToken)
        {
            try
            {
                List<string> paramName = new List<string>();
                List<object> paramValue = new List<object>();

                paramName.Add("Token");
                paramValue.Add(token);

                paramName.Add("Latitude");
                paramValue.Add(latitude);

                paramName.Add("Longitude");
                paramValue.Add(longtitude);

                if (localTime != null)
                {
                    paramName.Add("LocalTime");
                    paramValue.Add(localTime);
                }

                if (!string.IsNullOrEmpty(deviceToken))
                {
                    paramName.Add("deviceToken");
                    paramValue.Add(deviceToken);

                    //SendNotification(deviceToken, token);
                }

                DataTable dt = DataAccess.GetDataTable("spAPI_User_Ping", paramName.ToArray(), paramValue.ToArray());
                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { "<PingResponse>" + dt.Rows[0]["Result"].ToString() + "</PingResponse>" }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        void SendNotification(string deviceToken, string userToken)
        {
            try
            {
                using (var br = new PushBroker())
                {
                    DataTable dt = DataAccess.GetDataTable("spAPI_GetInfoForAppleDevice '" + userToken + "'");
                    int pushesCount = Convert.ToInt32(dt.Rows[0]["PushesCount"]);
                    int messagesCount = Convert.ToInt32(dt.Rows[0]["MessagesCount"]);
                    string promotionsId = dt.Rows[0]["PromotionsId"].ToString();

                    if (pushesCount == 0 && messagesCount == 0) return;

                    string msg = "You have ";
                    if (pushesCount > 0) msg += pushesCount.ToString() + " new promotions";
                    if (messagesCount > 0)
                    {
                        if (pushesCount > 0) msg += " and ";
                        msg += messagesCount.ToString() + " new messages";
                    }

                    var appleCert = System.IO.File.ReadAllBytes(Server.MapPath("~/cert.p12"));

                    br.OnNotificationFailed += new PushSharp.Core.NotificationFailedDelegate(br_OnNotificationFailed);
                    br.OnServiceException += new PushSharp.Core.ServiceExceptionDelegate(br_OnServiceException);
                    br.OnChannelException += new PushSharp.Core.ChannelExceptionDelegate(br_OnChannelException);

                    br.RegisterAppleService(new PushSharp.Apple.ApplePushChannelSettings(appleCert, ConfigurationManager.AppSettings["ApplePushServicePassword"]));
                    br.QueueNotification(new PushSharp.Apple.AppleNotification()
                               .ForDeviceToken(deviceToken)
                               .WithAlert(msg)
                               .WithSound("sound.caf")
                               .WithBadge(pushesCount + messagesCount)
                               .WithCustomItem("deals", pushesCount)
                               .WithCustomItem("promotionsId", promotionsId)
                               .WithCustomItem("messages", messagesCount));
                    br.StopAllServices();
                }
            }
            catch (Exception ex)
            {
                System.IO.File.AppendAllText(Server.MapPath("~/Tmp/apple_errors.txt"), "\n" + DateTime.Now.ToString() + "\n" + ex.Message + "\n" + ex.StackTrace + "\n");
            }
        }

        void br_OnChannelException(object sender, PushSharp.Core.IPushChannel pushChannel, Exception error)
        {
            br_OnNotificationFailed(sender, null, error);
        }

        void br_OnServiceException(object sender, Exception error)
        {
            br_OnNotificationFailed(sender, null, error);
        }

        void br_OnNotificationFailed(object sender, PushSharp.Core.INotification notification, Exception error)
        {
            System.IO.File.AppendAllText(Server.MapPath("~/Tmp/apple_errors.txt"), "\n" + DateTime.Now.ToString() + "\n" + error.Message);
        }

        public string SendMessage(string token, string message, bool emailCopy = false)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("sp_API_User_SendMessage",
                    new string[] { "Token", "Message" }, new object[] { token, message });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                {
                    if ((!dt.Rows[0].IsNull("Email")) && emailCopy)
                        CommonLib.SendEmail(dt.Rows[0]["Email"].ToString(), "", "Zatify", message);

                    return CommonLib.OkXml().ToString();
                }
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string GetMessages(string token)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_UserBusiness_GetMessages",
                    new string[] { "Token", "TokenType" }, new object[] { token, "U" });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string GetPromotionDetails(string token, int promotionId)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_User_GetPromotionDetails",
                    new string[] { "Token", "PromotionId" }, new object[] { token, promotionId });

                switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                {
                    case 1:
                        return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
                    case -1:
                        return CommonLib.ErrorXml("Promotion not found", "2").ToString();
                    default:
                        return CommonLib.ErrorXml("Invalid token", "1").ToString();
                }
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }
    }
}
